﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Data;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.IO;
using System.Reflection;
using System.Diagnostics;

namespace TAMSUP
{
    /// <summary>
    /// Interaction logic for Backup.xaml
    /// </summary>
    public partial class BackUp : Window
    {
        DataTable dtServers;
        public static Server srvr;
        private int state = 1;

        public BackUp()
        {
            InitializeComponent();

            try
            {
                dtServers = SmoApplication.EnumAvailableSqlServers();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + ex.Message, "Error : Connection Not Established");
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            label2.Visibility = System.Windows.Visibility.Hidden;
            label3.Visibility = System.Windows.Visibility.Hidden;
            serverBox.Visibility = System.Windows.Visibility.Hidden;
            databaseBox.Visibility = System.Windows.Visibility.Hidden;
            backupButton.Content = "Log in";
        }

        private void backupButton_Click(object sender, RoutedEventArgs e)
        {
            if (state == 1)
            {
                if (passwordBox1.Password.Equals("yasjdg528088"))
                {
                    labelPerintah.Visibility = System.Windows.Visibility.Hidden;
                    labelPassword.Visibility = System.Windows.Visibility.Hidden;
                    passwordBox1.Visibility = System.Windows.Visibility.Hidden;
                    label2.Visibility = System.Windows.Visibility.Visible;
                    label3.Visibility = System.Windows.Visibility.Visible;
                    serverBox.Visibility = System.Windows.Visibility.Visible;
                    databaseBox.Visibility = System.Windows.Visibility.Visible;
                    backupButton.Content = "Choose";
                    try
                    {
                        //chk_Insec.Checked = true;

                        // If there are any servers
                        if (dtServers.Rows.Count > 0)
                        {
                            // Loop through each server in the DataTable
                            foreach (DataRow drServer in dtServers.Rows)
                            {
                                serverBox.Items.Add(drServer["Name"]);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("ERROR: There are no available servers.\nOr there is an error while loading server name", "Server Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    state = 2;
                }
                else
                {
                    MessageBox.Show("ERROR: Password yang anda masukkan salah", "Error", MessageBoxButton.OK,
                        MessageBoxImage.Error);
                }
            }
            else
            {
                var directory = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                var file = System.IO.Path.Combine(directory, "log.tam");

                TextWriter tw = new StreamWriter(file);

                tw.Write("Data Source=" + serverBox.SelectedItem.ToString() + ";Initial Catalog=\"" + databaseBox.SelectedItem.ToString() + "\";Integrated Security=True");

                tw.Close();

                this.Close();
            }
        }

        private void penggunaWindow_Closed(object sender, EventArgs e)
        {
        }

        private void databaseBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
        }

        private void serverBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            databaseBox.Items.Clear();
            try
            {
                if (serverBox.SelectedItem != null && serverBox.SelectedItem.ToString() != "")
                {
                    this.Cursor = Cursors.Wait;
                    // Create a new connection to the selected server name
                    ServerConnection srvConn = new ServerConnection(serverBox.SelectedItem.ToString());
                    // Log in using SQL authentication instead of Windows authentication
                    srvConn.LoginSecure = true;
                    // Create a new SQL Server object using the connection we created
                    srvr = new Server(srvConn);
                    // Loop through the databases list
                    foreach (Database dbServer in srvr.Databases)
                    {
                        // Add database to combobox
                        databaseBox.Items.Add(dbServer.Name);
                    }
                }
                else
                {
                    // A server was not selected, show an error message
                    MessageBox.Show("ERROR: Contact Administrator!!", "Server", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("ERROR: An error ocurred while loading the avaiable databases", "Server", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }

        private void passwordBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (passwordBox1.Password.Equals("yasjdg528088"))
                {
                    labelPerintah.Visibility = System.Windows.Visibility.Hidden;
                    labelPassword.Visibility = System.Windows.Visibility.Hidden;
                    passwordBox1.Visibility = System.Windows.Visibility.Hidden;
                    label2.Visibility = System.Windows.Visibility.Visible;
                    label3.Visibility = System.Windows.Visibility.Visible;
                    serverBox.Visibility = System.Windows.Visibility.Visible;
                    databaseBox.Visibility = System.Windows.Visibility.Visible;
                    backupButton.Content = "Choose";
                    try
                    {
                        //chk_Insec.Checked = true;

                        // If there are any servers
                        if (dtServers.Rows.Count > 0)
                        {
                            // Loop through each server in the DataTable
                            foreach (DataRow drServer in dtServers.Rows)
                            {
                                serverBox.Items.Add(drServer["Name"]);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("ERROR: There are no available servers.\nOr there is an error while loading server name", "Server Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    state = 2;
                }
                else
                {
                    MessageBox.Show("ERROR: Password yang anda masukkan salah", "Error", MessageBoxButton.OK,
                        MessageBoxImage.Error);
                }
            }
        }
    }
}
